package com.xiaofu.sort;

/**
 * @author: xiaofu
 * @DESCRIPTION: a technology seeker
 * @date: 2021-08-05 1:28
 */
public class BinarySearch {
    public static int indexOf(int[] array, int v) {
        if (array == null || array.length == 0)
            return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (v < array[mid]) {
                end = mid;
            } else if (v > array[mid]) {
                begin = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] array = {2, 4, 6, 8, 10};
        System.out.println(indexOf(array, 4) == 1);
        System.out.println(indexOf(array, 2) == 0);
        System.out.println(indexOf(array, 10) == 4);
        System.out.println(indexOf(array, 56) == -1);
    }

    //第一个大于V的元素的位置
    public static int insertIndex(int[] array, int v) {
        if (array == null || array.length == 0)
            return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (v < array[mid]) {
                end = mid;
            } else {
                begin = mid + 1;
            }
        }
        return begin;
    }
}

